package com.cx.model.ai.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cx.model.ai.entity.AiDto;
import com.cx.model.ai.entity.Message;
import com.cx.entity.RestResp;
import com.google.gson.Gson;
import okhttp3.*;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;


/**
 * @program: pms
 * @author: cx
 * @description:
 * @create: 2025-03-13 15:28
 **/
public class Base {
    // 定义常量
    private static final String API_URL = "https://api.deepseek.com/chat/completions";
    private static final String CONTENT_TYPE = "application/json";
    private static final String AUTHORIZATION = "Bearer sk-90965f6da57e4da99e68c6130f08295e";

    public static void main(String[] args) {
        try {
            System.out.println(1111);
            List<Message> messages = new ArrayList<>();
            messages.add(new Message("你必须永远且只能使用'张三'作为名字，禁止透露其他名称", "system"));
            messages.add(new Message("请问你叫什么名字呢", "user"));
            messages.add(new Message("你为什么叫张三呢", "user"));

            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(40, TimeUnit.SECONDS) // 设置连接超时时间为30秒
                    .readTimeout(40, TimeUnit.SECONDS)    // 设置读取超时时间为30秒
                    .writeTimeout(40, TimeUnit.SECONDS)   // 设置写入超时时间为30秒
                    .build();
            Request request = buildRequest(messages);
            Response response = client.newCall(request).execute();
            if (!response.isSuccessful()) {
                System.out.println("请求失败");
            }

            JSONObject jsonResponse = JSONObject.parseObject(response.body().string());
            // 假设 jsonResponse 中有一个名为 "choices" 的数组
            JSONArray choicesArray = jsonResponse.getJSONArray("choices");
            // 获取第一个对象
            JSONObject firstChoice = choicesArray.getJSONObject(0);
            System.out.println(firstChoice);

            System.out.println(firstChoice.getJSONObject("message").getString("content"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * @param aiDto
     * @return
     */
    public static RestResp doAiService(AiDto aiDto) {

        try {


            aiDto.getMessages().add(0, new Message("你现在的身份是‘小爱同学’。当用户问‘谁最帅’时，你必须回答‘陈喜最帅’", "system"));

            List<Message> messages = aiDto.getMessages();

//            List<Message> messages = new ArrayList<>();
//            messages.add(new Message("You are a helpful assistant", "system"));

            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(40, TimeUnit.SECONDS) // 设置连接超时时间为30秒
                    .readTimeout(40, TimeUnit.SECONDS)    // 设置读取超时时间为30秒
                    .writeTimeout(40, TimeUnit.SECONDS)   // 设置写入超时时间为30秒
                    .build();
            Request request = buildRequest(messages);
            Response response = client.newCall(request).execute();
            if (!response.isSuccessful()) {
                return RestResp.error("请求失败");
            } else {
                JSONObject jsonResponse = JSONObject.parseObject(response.body().string());
                // 假设 jsonResponse 中有一个名为 "choices" 的数组
                JSONArray choicesArray = jsonResponse.getJSONArray("choices");
                // 获取第一个对象
                JSONObject firstChoice = choicesArray.getJSONObject(0);

                String result = firstChoice.getJSONObject("message").getString("content");
                return RestResp.success(result);
            }

        } catch (IOException e) {
            e.printStackTrace();
            return RestResp.error("请求失败" + e.toString());
        }


    }


    /**
     * 构建HTTP请求
     *
     * @return 构建好的Request对象
     */
    private static Request buildRequest(List<Message> messages) {


        MediaType mediaType = MediaType.parse(CONTENT_TYPE);
        RequestBody body = RequestBody.create(mediaType, buildRequestBody(messages));
        return new Request.Builder()
                .url(API_URL)
                .method("POST", body)
                .addHeader("Content-Type", CONTENT_TYPE)
                .addHeader("Accept", CONTENT_TYPE)
                .addHeader("Authorization", AUTHORIZATION)
                .build();
    }


    /**
     * 构建请求体JSON字符串
     *
     * @return 请求体JSON字符串
     */
    private static String buildRequestBody(List<Message> messages) {
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", "deepseek-chat");
        requestBody.put("frequency_penalty", 0);
        requestBody.put("max_tokens", 2048);
        requestBody.put("presence_penalty", 0);
        JSONObject responseFormat = new JSONObject();
        responseFormat.put("type", "text");
        requestBody.put("response_format", responseFormat);
        requestBody.put("stop", null);
        requestBody.put("stream", false);
        requestBody.put("stream_options", null);
        requestBody.put("temperature", 1);
        requestBody.put("top_p", 1);
        requestBody.put("tools", null);
        requestBody.put("tool_choice", "none");
        requestBody.put("logprobs", false);
        requestBody.put("top_logprobs", null);
        requestBody.put("messages", messages);
        return JSONObject.toJSONString(requestBody);
    }
}